package com.qfedu.department.controller;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.qfedu.common.entity.WoPage;
import com.qfedu.common.entity.WoResultCode;
import com.qfedu.common.exception.handler.WoControllerExceptionHandler;
import com.qfedu.department.dto.LeaveDto;
import com.qfedu.department.service.LeaveService;
import com.qfedu.psys.dto.MenuDto;
import com.qfedu.psys.service.CoreService;
import com.qfedu.psys.util.PSysConstant;
import com.qfedu.psys.util.PSysUtil;

@Controller
@RequestMapping("/dpt/leave")
@SessionAttributes(names=PSysConstant.SESSION_USER)
public class LeaveController {
	private final static Logger LOG = LogManager.getLogger(LeaveController.class);
	
	/**
	 * 注入MenuService
	 */
	@Resource
	private CoreService coreService;
		
	/**
	 * 注入LeaveService
	 */
	@Resource
	private LeaveService leaveService;
	
	/**
	 * 注入异常处理器.
	 */
	@Resource
	private WoControllerExceptionHandler exceptionHandler;
	
	/**
	 * 加载我的请假的管理页面
	 * @return
	 */
	@RequestMapping("/me")
	public String myLeaves (Map<String, Object>map) {
		return exceptionHandler.toLoginView(() -> {
			List<MenuDto> menus = coreService.getMenus(PSysUtil.getCurrentUser(map), "menu-dpt", "menu-myLeaves");
			map.put("menus", menus);
		}, map, "dpt/leave-me");
	}
	
	/**
	 * 当我的请假的管理页面加载完毕，前端会发送Ajax请求列表数据
	 * @return
	 */
	@RequestMapping("/me/list")
	public String myLeaveList (String searchContent, @RequestParam(defaultValue = "1") Long page, Map<String, Object>map) {
		return this.exceptionHandler.toAjaxErrorView(() -> {
			WoPage<LeaveDto> pageData = leaveService.getPageData (PSysUtil.getCurrentUser(map), searchContent, page, WoPage.SIZE);
			map.put("pageData", pageData);
		}, map, "dpt/leave-me-list");
	}
	
	/**
	 * 加载请假创建表单.
	 * @param map
	 * @return
	 */
	@GetMapping("/me/create")
	public String create(Map<String, Object> map) {
		return "dpt/leave-me-create";
	}
	
	/**
	 * 提交请假创建表单.
	 * @param dto
	 * @param map
	 * @return
	 */
	@PostMapping("/me/create")
	@ResponseBody
	public WoResultCode create(LeaveDto dto, Map<String, Object> map) {
		return exceptionHandler.toJsonView(() -> leaveService.create(PSysUtil.getCurrentUser(map), dto), "创建请假申请成功！");
	}
}
